package com.example.auth;

import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.jdbc.JDBCClient;
import io.vertx.ext.web.RoutingContext;
import org.mindrot.jbcrypt.BCrypt;

public class AuthHandler {
    private final JDBCClient db;
    private final JwtProvider jwtProvider;

    public AuthHandler(JDBCClient db, JwtProvider jwtProvider) {
        this.db = db;
        this.jwtProvider = jwtProvider;
    }

    public void register(RoutingContext ctx) {
        JsonObject body = ctx.getBodyAsJson();
        String username = body.getString("username");
        String password = body.getString("password");
        String email = body.getString("email");

        String hashed = BCrypt.hashpw(password, BCrypt.gensalt());
        JsonArray params = new JsonArray().add(username).add(hashed).add(email);
        db.updateWithParams("INSERT INTO users (username, password, email) VALUES (?, ?, ?)", params, res -> {
            if (res.succeeded()) {
                ctx.response().setStatusCode(201).end("注册成功");
            } else {
                ctx.response().setStatusCode(500).end("注册失败");
            }
        });
    }

    public void login(RoutingContext ctx) {
        JsonObject body = ctx.getBodyAsJson();
        String username = body.getString("username");
        String password = body.getString("password");

        db.queryWithParams("SELECT * FROM users WHERE username = ?", new JsonArray().add(username), res -> {
            if (res.succeeded() && res.result().getNumRows() > 0) {
                JsonObject user = res.result().getRows().get(0);
                String hash = user.getString("password");
                if (BCrypt.checkpw(password, hash)) {
                    String token = jwtProvider.generateToken(username);
                    ctx.response().putHeader("Content-Type", "application/json")
                        .end(new JsonObject().put("token", token).encode());
                } else {
                    ctx.response().setStatusCode(401).end("密码错误");
                }
            } else {
                ctx.response().setStatusCode(404).end("用户不存在");
            }
        });
    }
}